#!/bin/bash

# 安装目标目录
INSTALL_DIR="/tmp/go"

# 获取最新版本号
LATEST_VER=$(curl -s https://go.dev/VERSION?m=text | head -1)
LATEST_VER_NUM=${LATEST_VER#go}
echo "最新版本: $LATEST_VER_NUM"

# 是否跳过 Go 安装
SKIP_GO_INSTALL=false

if [ -x "$INSTALL_DIR/bin/go" ]; then
    CURRENT_VER=$("$INSTALL_DIR/bin/go" version | awk '{print $3}' | sed 's/go//')
    echo "当前已安装版本: $CURRENT_VER"

    if [ "$CURRENT_VER" == "$LATEST_VER_NUM" ]; then
        echo "Go 已是最新版本 ($CURRENT_VER)，跳过安装。"
        SKIP_GO_INSTALL=true
    else
        echo "当前版本较旧，将更新至 $LATEST_VER_NUM"
    fi
else
    echo "未检测到 Go，准备安装最新版 $LATEST_VER_NUM"
fi


if [ "$SKIP_GO_INSTALL" != "true" ]; then
    # 检测系统架构并映射Go版本后缀
    ARCH=$(uname -m)
    case $ARCH in
        x86_64)  GO_ARCH="amd64" ;;
        aarch64) GO_ARCH="arm64" ;;
        armv7l)  GO_ARCH="armv6l" ;;
        armv6l)  GO_ARCH="armv6l" ;;
        *)       echo "不支持的架构: $ARCH"; exit 1 ;;
    esac

    echo "检测到架构: $ARCH => 使用Go编译版本: $GO_ARCH"

    # 下载地址
    DOWNLOAD_URL="https://dl.google.com/go/${LATEST_VER}.linux-${GO_ARCH}.tar.gz"
    TARBALL="/tmp/${LATEST_VER}.linux-${GO_ARCH}.tar.gz"
    echo "下载地址: $DOWNLOAD_URL"
    echo "保存到: $TARBALL"

    # 清理旧目录并创建新安装目录
    rm -rf "$INSTALL_DIR"
    mkdir -p "$INSTALL_DIR" || { echo "创建目录失败"; exit 1; }

    # 下载并解压
    echo "正在下载并安装..."
    curl -o "$TARBALL" "$DOWNLOAD_URL" || { echo "下载失败"; exit 1; }
    tar -C "$INSTALL_DIR" -xzf "$TARBALL" || { echo "解压失败"; exit 1; }

    # 整理目录结构（处理自带的 go/ 子目录）
    if [ -d "$INSTALL_DIR/go" ]; then
        echo "调整目录结构..."
        mv "$INSTALL_DIR/go/"* "$INSTALL_DIR/"
        rmdir "$INSTALL_DIR/go"
    fi

    # 设置环境变量（仅当前会话）
    # export GOROOT="$INSTALL_DIR"
    # export PATH="$PATH:$GOROOT/bin"

    # 验证安装
    echo "验证安装:"
    # go version || { echo "安装验证失败"; exit 1; }
    $INSTALL_DIR/bin/go version || { echo "安装验证失败"; exit 1; }

    # 清理安装包
    rm "$TARBALL"

    echo "安装完成！GOROOT 设置为 $GOROOT"
fi

# =========================
# 🚀 Go 安装部分到此结束
# ✅ 在这里继续其他脚本逻辑
# =========================

echo "继续执行其他操作..."

# 修复识别内存错误导致 tmp 小于内存
mount -o remount,size=$(awk '/MemTotal/ {print $2"k"}' /proc/meminfo) /tmp

# 临时目录与缓存设置
export TMPDIR=/tmp/gotmp
export GOCACHE=/tmp/gocache
export GOMODCACHE=/tmp/gomodcache
mkdir -p "$TMPDIR" "$GOCACHE" "$GOMODCACHE"

# 国内 Go 模块加速
cd /data/gocode
"$INSTALL_DIR/bin/go" env -w GO111MODULE=on
"$INSTALL_DIR/bin/go" env -w GOPROXY=https://goproxy.cn,direct
"$INSTALL_DIR/bin/go" mod init youxuan
"$INSTALL_DIR/bin/go" mod tidy

# 运行主程序
"$INSTALL_DIR/bin/go" run /data/gocode/youxuan.go > /tmp/youxuan.log 2>&1

# 清理临时缓存（可选，拉胯路由器 可跳过）
# rm -rf "$TMPDIR" "$GOCACHE" "$GOMODCACHE"
rm -rf /tmp/gotmp
#rm -rf /tmp/gocache
#rm -rf /tmp/gomodcache